import urllib.request as ur
import argparse as ap
import sys

# 文件路径分割符
path_div = None
if sys.platform.startswith("win32"):
    path_div = "\\"
else:
    path_div = "/"

# 线上判定系统的网络地址
host = "172.20.20.59"

Cookie = None           

payload       = b""               # 要提交的文件内容
problemID     = 0                 # 问题ID    (必要动态参数)
assignID      = 197               # 意义不明  (必要且固定)
javaMainClass = ""                # java主类名
proNum        = 1                 # 意义不明  (非必要)
courseID      = 2                 # 课程代码  (非必要）
language      = None

parser = ap.ArgumentParser(description="(半)自动化提交工具")
parser.add_argument("file",type=str,help="需提交的文件")
parser.add_argument("cls",type=str,help="主类名")
parser.add_argument("--proNum",type=str,help="问题序列(意义未明)",default="1")
parser.add_argument("-lang",type=str,help="指定编程语言(默认Java)",default="java")
parser.add_argument("problemID",type=str,help="问题ID")
argv = parser.parse_args()
problemID = argv.problemID
javaMainClass = argv.cls
language = argv.lang
proNum = argv.proNum
file = open(argv.file,"rb")
payload = file.read()
file.close()
cok = open("Cookie","r")
Cookie = cok.read()
cok.close()
Referer = "http://{}/assignment/programList.jsp?proNum={}&courseID={}&assignID={}".format(host,proNum,courseID,assignID)
header = {
    "Host":host,
    "Origin":"http://{}".format(host),
    "DNT":"1",
    "Content-Type":"multipart/form-data; boundary=----WebKitFormBoundarylZo68ON75zEdvOvG",
    "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36",
    "Referer":Referer,
    "Cookie":Cookie,
    "Content-Length":""
}

payload_name = argv.file.split(path_div)[-1].encode()

file_upload_url = "http://{}/assignment/showProcessMsg.jsp?problemID={}&assignID={}&doSubmit=true&progLanguage={}&javaMainCLass={}&wtime=34".format(host,problemID,assignID,language,javaMainClass)
upload_data = b'------WebKitFormBoundarylZo68ON75zEdvOvG\r\n'+\
       b'Content-Disposition: form-data; name="FILE1"; filename="'+payload_name+b'"\r\n'+\
       b'Content-Type: application/octet-stream\r\n\r\n'+\
       payload+b'\r\n\r\n'+\
       b'------WebKitFormBoundarylZo68ON75zEdvOvG--\r\n'

header["Content-Length"] = str(len(upload_data))

commit_file = ur.Request(url=file_upload_url, data=upload_data,headers=header,method="POST")

conn = ur.urlopen(commit_file)

conn.close()